package parser

import (
	"learngo/crawler/engine"
	"learngo/crawler/model"
	"regexp"
	"strconv"
)

var ageRe = regexp.MustCompile(`<span class="age s1">([\d]+)岁</span>`)
var genderRe = regexp.MustCompile(`<span>
([^<]+ )</span>
<span class="marrystatus">`)
var marriageRe = regexp.MustCompile(`<span class="marrystatus">([^<]+)</span>`)
var heightRe = regexp.MustCompile(`<span class="height">([^<]+)</span>`)
var educationRe = regexp.MustCompile(`<span class="education">([^<]+)</span>`)
var incomeRe = regexp.MustCompile(`<li>收入：<span>([^<]+)</span></li>`)
var addressRe = regexp.MustCompile(`<li>现居：<span>([^<]+)</span></li>`)

func ParseProfile(contents []byte, name string) engine.ParseResult {
	profile := model.Profile{}

	profile.Name = name

	age, err := strconv.Atoi(extractString(contents, ageRe))
	if err == nil {
		profile.Age = age
	}

	//profile.Gender = extractString(contents, genderRe)
	profile.Marriage = extractString(contents, marriageRe)
	profile.Height = extractString(contents, heightRe)
	profile.Education = extractString(contents, educationRe)
	profile.Income = extractString(contents, incomeRe)
	profile.Address = extractString(contents, addressRe)

	result := engine.ParseResult{
		Items: []interface{}{profile},
	}

	return result
}

func extractString(contents []byte, re *regexp.Regexp) string {
	match := re.FindSubmatch(contents)
	if len(match) >= 2 {
		return string(match[1])
	}else {
		return ""
	}
}
